<?php 

	include 'payform_view.php';
	include 'payment_settings.php';
	include 'payment_status.php';
	

	function generateRandomString($length = 10) {
	    $characters = 'STUVlmnopqrstuvdefwxyzAB0123CDEFGghijkabcWXYZ456789HIJKLMNOPQR';
	    $randomString = '';
	    for ($i = 0; $i < $length; $i++) {
	        $randomString .= $characters[rand(0, strlen($characters) - 1)];
	    }
	    return $randomString;
	}




	function payment( $table_data ){



		$clientcourse_id = $table_data['clientcourse_id'];
		checkPaymentCourse($clientcourse_id);

		$prefix = "timetable_";
		global $wpdb;
		$q = "SELECT SUM(payment_amount) amount FROM {$prefix}payment WHERE clientcourse_id = $clientcourse_id ";
		$res = $wpdb->get_row($q, ARRAY_A);
		$amount = $res['amount'];
		$q = "SELECT course_basecost, course_name,  client_id, paystatus_id FROM {$prefix}clientcourse, {$prefix}course WHERE  idcourse = course_id  AND idclientcourse = $clientcourse_id ";
		$res = $wpdb->get_row($q, ARRAY_A);
		$basecost = $res['course_basecost'];
		$course_name = $res['course_name'];
		$client_id = $res['client_id'];
		$paystatus_id = $res['paystatus_id'];

		$qu = "SELECT user_id, client_name FROM {$prefix}client WHERE idclient = $client_id ";
		$user = $wpdb->get_row($qu, ARRAY_A);
		$client_name = $user['client_name'];
		
		$str_payment_name = "Оплата за курс '{$course_name}'. Плательщик {$client_name}.";

		if($amount == null){
			$amount = 0;
		}



		if( ($basecost <= $amount) || ( $paystatus_id == 3 ) )  {
			
		}else{

			$div =  ($basecost - $amount)/$basecost;

			$list = array();

			//echo "div $div  <br>";
			//echo "basecost $basecost  <br>";
			//echo "amount $amount  <br>";

			//init 
			//create new order 

			$sql_t = "SELECT now() time";
			$res_t = $wpdb->get_row($sql_t, ARRAY_A);
			$res_t = $res_t['time'];
			$res_t = str_replace('-', '', $res_t);
			$res_t = str_replace(' ', '', $res_t);
			$res_t = str_replace(':', '', $res_t);

			$sql_c = "SELECT COUNT(*) count FROM {$prefix}order_new";
			$res_c = $wpdb->get_row($sql_c, ARRAY_A);
			$res_c = $res_c['count'];

			$format = '%1$09d';
			$res_f = sprintf($format, $res_c+1);
			$res_order = $res_f."_".$res_t."_".generateRandomString(39);

			//echo "res_order $res_order <br>";
			
			//order_id  			

			$order_id = $res_order;
			$wpdb->insert("{$prefix}order_new", array('order_number'=>$res_order, 'clientcourse_id'=>$clientcourse_id, 'user_id'=>$user['user_id']));
			$last_id = $wpdb->insert_id;

			//echo "last_id $last_id <br>";

			$res_valid = $wpdb->get_row( "SELECT order_number FROM ${prefix}order_new WHERE idorder = $last_id", ARRAY_A);
			//echo   json_encode($res_valid)."<br>";
	
			$valid = '';
			if($res_valid['order_number'] == $res_order){
				$valid = true;
			}else{
				$valid = false;
			};

				$project = 	payment_settings();
				$projectid = $project['projectid'];
			
			//amount + extra
			$list_extra = array();

			if( $div == 1 ){
				$list = array(
					array( "projectid"=>$projectid, "comment"=>"Первый платеж 1/3 суммы" , "amount"=>array("key"=> "1/3", "value" => round($basecost/3) ) ),
					array( "projectid"=>$projectid, "comment"=>"Первый платеж 1/2 суммы" , "amount"=>array("key"=> "1/2", "value" => round($basecost/2) ) ),
					array( "projectid"=>$projectid, "comment"=>"Полная оплата" ,  "amount"=>array("key"=> "1" , "value"  => $basecost ) )
				);					
			}elseif($div > 0.65){
				$list = array(
					array( "projectid"=>$projectid, "comment"=>"Второй платеж 1/3 суммы", "amount"=>array("key"=> "1/3", "value" => round($basecost/3) ) ),
					array( "projectid"=>$projectid, "comment"=>"Второй платеж оставшаяся сумма", "amount"=>array("key"=> "1" , "value"  => ($basecost - $amount) ) )
				);					
			}elseif($div <=0.5){	
				$list = array(
					array( "projectid"=>$projectid, "comment"=>"Последний платеж оставшаяся сумма", "amount"=>array("key"=> "1" , "value"  => ($basecost - $amount) ) )
				);					
			}


			//nickname
			$user = UsersORM::getUser(true);
			$nickname = $user['id'];

			// response urls
			$return_url_success = plugins_url("payment_succes.php", __FILE__);
			$return_url_fail = plugins_url("payment_fail.php", __FILE__);

			payform_view($valid, $list, $order_id, $nickname, $return_url_success, $return_url_fail, $course_name, $div, $str_payment_name);

		}
	}
?>